import { defineStore } from 'pinia';
import { ref, watch } from "vue";
export const useIsChosenStore = defineStore('isChosen', () => {
	const isChosen = ref([
		{shop: true, product: [true, false]}, 
		{shop: false, product: [false, true, false]}
	]);
	const isAllChosen = ref(false);
	const isInactiveProductChosen = ref(
		[false, true]
	)
	const computePrice = ref(false); // 用于触发总价计算
	
	// 初始请求数据后对isChosen初始化
	function initIsChosen(newData){
		isChosen.value = newData
	}
	// 初始请求数据后对isInactiveProductChosen初始化
	function initIsInactiveProductChosen(newData){
		isInactiveProductChosen.value = newData
	}
	
	function updateIsChosen(newData, idxOfShop, idxOfProduct = -1){
		// 更新isChosen的shop属性
		if(idxOfProduct === -1){
			isChosen.value[idxOfShop].shop = newData;
			// 对应更新product属性
			if((newData ===false && isChosen.value[idxOfShop].product.every((item)=>item===true))
				|| newData === true)
				{
					isChosen.value[idxOfShop].product.fill(newData);
				}
		}
		// 更新isChosen的product属性
		else{
			isChosen.value[idxOfShop].product[idxOfProduct] = newData;
			// 对应更新shop属性
			isChosen.value[idxOfShop].shop = isChosen.value[idxOfShop].product.every((item)=>item===true);
		}
		
		// 更新isAllChosen
		if(newData){
			let t = true;
			isChosen.value.forEach((item)=>{
				t &= item.shop;
			})
			isAllChosen.value = t;
		}
		else{
			isAllChosen.value = false;
		}
		
		// 用于触发总价计算
		computePrice.value = !computePrice.value;
	}
	
	function updateIsChosenByIsAllChosen(){
		const value = isAllChosen.value;
		isChosen.value.forEach((it)=>{
			it.shop = value;
			it.product.fill(value);
		})
	}
	
	function updateIsInactiveProductChosen(newData, idxOfProduct){
		isInactiveProductChosen.value[idxOfProduct] = newData;
	}

	return { 
		isChosen,
		isAllChosen,
		isInactiveProductChosen,
		computePrice,
		
		initIsChosen,
		initIsInactiveProductChosen,
		
		updateIsChosen,
		updateIsChosenByIsAllChosen,
		updateIsInactiveProductChosen
	};
});
